<template>
<div class="app-container">
      <custom-query :items="item" @query="query"></custom-query>    
      <el-row :gutter="24" style="margin-left:-12px;margin-right:-10px">
            <el-col :span="17" >
              <custom-table-grid ref="sonRolesListGrid"
                              :column-data="columndata"
                                :url="getSonRolesListUrl"
                                :param="param"
                                :is-need-check-box="false"
                                :toolbar="toolbar"
                                @row-click="queryMenuByRole">
              </custom-table-grid>
            </el-col>
            <el-col :span="7">
              <el-card style="width:100%;overflow:auto;margin-top:15px" class="role-tree" shadow="never">
                  <custom-btn style="margin-bottom:15px" btn-type="save" @btn-click="roleAddMenu" :label="this.$t('button.save')" ></custom-btn>
                  <el-tree :data="treeData" 
                  :props="defaultProps"
                  :default-expanded-keys="[this.rootId]"
                  ref="tree" 
                  :show-checkbox='true'
                  node-key = "id" >
                  </el-tree>
              </el-card>
            </el-col>
      </el-row>
    <el-dialog :title="dialogTitle" width="65%" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="validateForm" ref="addOrEditForm">
        <el-form-item :label="_$Z['roleName']" :label-width="formLabelWidth"  prop="roleName" :rules="filter_rules({required:true,length:[-1,50],spChar:true})">
                 <el-input type="roleName" v-model.trim="form.roleName" auto-complete="off"  style="width:200px"></el-input>
        </el-form-item>
        <el-form-item :label="_$Z['status']" :label-width="formLabelWidth" prop="status">
          <custom-combox v-model="form.status" code-type="role_type" style="width:200px" :isAll=false ></custom-combox>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <custom-btn btn-type="cancel" @btn-click="cancel" :label="this.$t('common.cancel')"></custom-btn>
        <custom-btn btn-type="confirm" @btn-click="save" :label="this.$t('common.confirm')"></custom-btn>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import customQuery from '@/views/platform/components/queryCondition/customQuery'
import customTableGrid from '@/views/platform/components/tableGrid/customTableGrid'
import customCombox from '@/views/platform/components/selector/customCombox'
import { query, post } from '@/api/common'

export default {
  name: 'platform_authority_role',
  components: { customQuery, customTableGrid, customCombox },
  data() {
    return {
      i18Keys: ['roleName', 'status', 'add', 'edit', 'query', 'configRole', 'updateTime', 'selectOneRole'],
      getSonRolesListUrl: '/common/role/getSonRolesList',
      addRoleSaveUrl: '/common/role/addRole',
      editRoleSaveUrl: '/common/role/editRole',
      queryTreeUrl: '/common/role/menuTree',
      queryMenuByRoleUrl: '/common/role/queryMenuByRole',
      saveRoleAndMenuUrl: '/common/role/roleAddMenu',
      deleteRoleUrl: 'common/role/deleteRole',
      formLabelWidth: '250px',
      form: {
        roleName: '',
        status: '',
        roleId: ''
      },
      currentNodeKey: '',
      queryForm: {
        roleName: '',
        status: ''
      },
      dialogFormVisible: false,
      validateForm: {
        roleName: [{ required: true, message: 'Please Enter!', trigger: 'blur' }],
        status: [{ required: true, message: 'Please Choose!', trigger: 'change' }]
      },
      item: [
        { label: 'name2', elType: 'input', id: 'roleName' },
        { label: 'status', elType: 'select', id: 'status', codeType: 'role_type' }
      ],
      addOrEdit: '',
      treeData: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'menuName'
      },
      param: {},
      rootId: '',
      columndata: [
        { label: 'name2', prop: 'ROLENAME', sort: false },
        { label: 'status', prop: 'ROLESTATE', sort: false },
        { label: 'updateTime', prop: 'UPDATETIME', sort: false },
        { label: 'operation', prop: 'OP', type: 'operations', width: 120, operations: [
          { type: 'edit', label: 'edit', method: this.editRole },
          { type: 'delete', label: 'delete', method: this.deleteRole }
        ] }
      ],
      toolbar: [{
        type: 'add',
        label: 'add',
        method: this.addRole
      }],
      title: '',
      configRoleDialog: false,
      dialogTitle: ''
    }
  },

  mounted() {
    this.$refs.sonRolesListGrid.pageQuery(this.param)
    this.queryTree()
  },

  methods: {
    // 新增角色
    addRole() {
      this.addOrEdit = 'add'
      this.dialogFormVisible = true
      this.dialogTitle = this.$t('button.add')
    },
    // 编辑角色
    editRole(index, row) {
      this.addOrEdit = 'edit'
      this.dialogTitle = this.$t('button.edit')
      this.form = {
        roleName: row.ROLENAME,
        roleId: row.ROLEID,
        status: row.STATE
      }
      this.dialogFormVisible = true
    },

    save(form) {
      this.form.addOrEdit = this.addOrEdit
      this.$refs.addOrEditForm.validate((valid) => {
        if (valid) {
          post(this.form.addOrEdit === 'add' ? this.addRoleSaveUrl : this.editRoleSaveUrl, this.form).then(response => {
            this.$message({
              type: 'success',
              message: this.$t('message.saveSuccess')
            })
            this.dialogFormVisible = false
            this.form = {
              roleName: ''
            }
            this.query(this.queryForm)
          })
        }
      })
    },

    cancel() {
      this.form = {
        roleName: '',
        status: ''
      }
      this.dialogFormVisible = false
    },

    nodeClick(data) {
      const orgNo = data.nodeData['ORG_NO']
      this.defValue['orgNo'] = orgNo
      this.$refs.grid.pageQuery(this.defValue)
      this.currentNodeKey = orgNo
    },

    // 查询角色
    query(value) {
      this.queryForm = {
        roleName: value.roleName,
        status: value.status
      }
      this.$refs.sonRolesListGrid.pageQuery(value)
    },

    // 删除
    deleteRole(index, row) {
      this.$confirm(this.$t('message.confirmDelete'), this.$t('common.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel')
      }).then(() => {
        post(this.deleteRoleUrl, { roleId: row.ROLEID }).then(response => {
          const code = response.data.result_code
          if (code === '0') {
            this.$message({
              type: 'success',
              message: this.$t('message.deleteSuccess')
            })
            this.query(this.form)
          }
        })
      }).catch(() => {
        return
      })
    },

    queryTree() {
      query(this.queryTreeUrl).then(response => {
        this.treeData = response.data.data
      })
    },

    // 根据角色查询菜单 查询对应权限，并赋值权限树
    queryMenuByRole(index) {
      this.param = {
        roleId: index.ROLEID
      }
      this.currentNodeKey = index.ROLEID
      query(this.queryMenuByRoleUrl, this.param).then(response => {
        const nodeList = response.data.data
        const checkedKeys = []
        // 清空当前树的选择项
        this.$refs.tree.setCheckedKeys([])
        // 循环并选中
        nodeList.forEach(e => {
          checkedKeys.push(e.ID)
        })
        this.$refs.tree.setCheckedKeys(checkedKeys)
      })
    },

    // 角色绑定菜单
    roleAddMenu() {
      if (this.currentNodeKey) {
        const param = {
          checkNodeList: this.$refs.tree.getCheckedKeys(),
          checkHalfCheckedList: this.$refs.tree.getHalfCheckedKeys(),
          currentNodeKey: this.currentNodeKey
        }
        post(this.saveRoleAndMenuUrl, param).then(response => {
          const code = response.data.result_code
          if (code === '0') {
            this.$message({
              type: 'success',
              message: this.$t('message.saveSuccess')
            })
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: this._$Z['selectOneRole']
        })
        return
      }
    }

  }
}
</script>
<style lang="scss">
  .role-tree {
    .el-card__body {
      height: calc(100vh - 180px);
    }
  }
</style>
